package com.yxr.affairs;

import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.thoughtworks.xstream.XStream;
import com.yxr.affairs.api.Constans1;
import com.yxr.affairs.base.BaseSwipeBackActivity1;
import com.yxr.affairs.utils.ToastUtil;
import com.yxr.affairs.utils.Utils;
import com.yxr.affairs.xtem.EncodeXstream;
import com.yxr.affairs.yj.Data;
import com.yxr.affairs.yj.Param1;
import com.yxr.affairs.yj.Storeditem;

import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;

import static android.content.Context.MODE_PRIVATE;

public class YjActivity extends BaseSwipeBackActivity1 {


    @BindView(R.id.goback)
    ImageButton goback;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.activity_xuan)
    TextView activityXuan;
    @BindView(R.id.settingrule)
    RelativeLayout settingrule;
    @BindView(R.id.activity_2)
    TextView activity2;
    @BindView(R.id.settin)
    RelativeLayout settin;
    @BindView(R.id.rv_invest2)
    RecyclerView rvInvest2;
    @BindView(R.id.avtivity_jitong)
    RelativeLayout avtivityJitong;

    private String Honst;
    private String time;
    private int i = 5;
    ProgressDialog xh_pDialog;
    private int mYear;
    private int mMonth;
    private int mDay;
    private int mHoure;
    private int mInute;
    private int mSecond;
    private String i1s, i2s;

    private MessageAdapter adapter;
    private ArrayList<Storeditem> storeditems = new ArrayList<>();
    private DecimalFormat df = new DecimalFormat("###,##0.00");

    private String SoftVersion;
    private String DataServerIP;
    private String Key;
    private String DataServerPort;
    private String SoftName;
    private String mDeviceid;
    private String mUsercode;
    private String mUserpwd;
    private String mVersion;
    private String mHospitalid;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_yj;
    }

    @Override
    protected void initViews() {

        SharedPreferences sPreferences=getSharedPreferences("muser", MODE_PRIVATE);
        Key=sPreferences.getString("Key", "");
        DataServerIP=sPreferences.getString("DataServerIP", "");
        DataServerPort=sPreferences.getString("DataServerPort", "");
        mDeviceid=sPreferences.getString("mDeviceid", "");
        mUsercode=sPreferences.getString("mUsercode", "");
        mUserpwd=sPreferences.getString("mUserpwd", "");
        mVersion=sPreferences.getString("mVersion", "");
        mHospitalid=sPreferences.getString("mHospitalid", "");

        adapter = new MessageAdapter(mContext, storeditems);
        rvInvest2.setLayoutManager(new LinearLayoutManager(YjActivity.this));
        rvInvest2.setAdapter(adapter);
        goback.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        settin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getSend();
            }
        });


        //系统前一天的时间

        SimpleDateFormat df = new SimpleDateFormat("yyyy.MM.dd");
        String cDate = df.format(new Date());
        Calendar c = Calendar.getInstance();
        Date date = null;
        try {
            date = new SimpleDateFormat("yy.MM.dd").parse(cDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        c.setTime(date);
        int day = c.get(Calendar.DATE);
        c.set(Calendar.DATE, day - 1);

        String dayBefore = new SimpleDateFormat("yyyy.MM.dd").format(c.getTime());

        activity2.setText(dayBefore);
        time = dayBefore;
        if (!Utils.isNetworkConnected(mContext)) {
            Toast.makeText(mContext, getString(R.string.network_hint), Toast.LENGTH_SHORT).show();
            return;
        }
        QueryAddressTask queryAddressTask = new QueryAddressTask();
        queryAddressTask.execute(Honst, time, i + "");

    }


    public void getSend() {

        Calendar ca = Calendar.getInstance();
        mYear = ca.get(Calendar.YEAR);
        mMonth = ca.get(Calendar.MONTH);
        mDay = ca.get(Calendar.DAY_OF_MONTH);

        new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {

            @Override
            public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {


                if (i1 < 9) {
                    i1s = "0" + (i1 + 1);
                } else {
                    i1s = "" + (i1 + 1);
                }

                if (i2 < 10) {
                    i2s = "0" + i2;
                } else {
                    i2s = "" + i2;
                }

                Log.e("birthId", (i + "" + i1s + "-" + "" + i2));

                activity2.setText(i + "." + i1s + "." + i2s);
                //   activity_2.setText((i +i1s+i2s+mHoure+mInute+mSecond).format("%Y-%m-%d %H:%M:%S"));
                Honst = activity2.getText().toString();
                time = activity2.getText().toString();

                if (!Utils.isNetworkConnected(mContext)) {
                    Toast.makeText(mContext, getString(R.string.network_hint), Toast.LENGTH_SHORT).show();
                    return;
                }
                QueryAddressTask queryAddressTask = new QueryAddressTask();
                queryAddressTask.execute(Honst, time, i + "");
            }
        }, mYear, mMonth, mDay).show();


        Log.i("birthday2", mYear + "--" + mMonth + "--" + Integer.parseInt(String.valueOf(mDay - 1)));
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    class QueryAddressTask extends AsyncTask<String, Integer, String> {
        @Override
        protected void onPreExecute() {
            xh_pDialog = new ProgressDialog(YjActivity.this);

            // 设置进度条风格，风格为圆形，旋转的
            xh_pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            xh_pDialog.setTitle("正在加载，请稍等");
            xh_pDialog.setIndeterminate(false);

            // 设置ProgressDialog 是否可以按退回键取消
            xh_pDialog.setCancelable(true);

            // 让ProgressDialog显示
            xh_pDialog.show();

        }

        protected String doInBackground(String... params) {
            // 查询手机号码（段）信息*/
            String result = null;

            try {
                result = getData(params[0]);


            } catch (Exception e) {

                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法

            Log.e("ADDADADggg", result);
            return result;
        }


        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            // 将WebService返回的结果显示在TextView中

            xh_pDialog.dismiss();

            if (result != null) {
                XStream xStream1 = new EncodeXstream("1.0", "gb2312");
                xStream1.alias("result", Data.class);
                xStream1.useAttributeFor(Param1.class, "size");
                xStream1.addImplicitCollection(Param1.class, "storeditems");
                xStream1.alias("storeditem", Storeditem.class);
                Data data1 = (Data) xStream1.fromXML(result);

                Log.e("TAG11", "status: " + data1.getStatus());
                Log.e("TAG11", "errorinfo: " + data1.getErrorinfo());
                Log.e("TAG11", "successinfo" + data1.getSuccessinfo());
                Log.e("TAG11", "param1 size: " + data1.getSuccessinfo().getParam1().getSize());

                Log.e("aadasf", result);

                try {

                    if (data1.getSuccessinfo().getParam1().getStoreditems() != null) {

                        avtivityJitong.setVisibility(View.VISIBLE);
                        storeditems.clear();
                        storeditems.addAll((ArrayList<Storeditem>) data1.getSuccessinfo().getParam1().getStoreditems());

                        adapter.setData(storeditems);
                        adapter.notifyDataSetChanged();
                    }else {

                        avtivityJitong.setVisibility(View.GONE);
                    }


                } catch (Exception e) {

                    e.printStackTrace();
                }
            }else {

                ToastUtil.toast(mContext,"网络异常,请检查!");
            }
        }
    }

    private String getData(String param) {
        String result = null;
        String WSDL_URI = "http://"+DataServerIP+":"+DataServerPort+"/soap/IHyWebServer";//wsdl 的uri
        String namespace = "urn:HyWebServerIntf-IHyWebServer";//namespace
        String methodName = "HyWebServiceIntfMethod";//要调用的方法名称

        SoapObject request = new SoapObject(namespace, methodName);

        String de = "<hywebserviceroot>" +
                "<funname>GetMbUserFunction</funname>" +
                "<hospitalid>"+mHospitalid+"</hospitalid>" +
                "    <key>"+Key+"</key>" +
                "    <deviceid>"+mDeviceid+"</deviceid>" +
                "    <usercode>"+mUsercode+"</usercode>" +
                "    <userpwd>"+mUserpwd+"</userpwd>" +
                "    <version>"+mVersion+"</version>" +
                "    <params>" +
                "     <param1><sFunName>GetYJXX</sFunName></param1>" +
                "     <param2><dL_RQ>" + time + " 00:00:00" + "</dL_RQ><sHospitalID></sHospitalID><LX>8</LX></param2>" +
                "    </params>" +
                "</hywebserviceroot>";

        request.addProperty("aXml", de);
        //创建SoapSerializationEnvelope 对象，同时指定soap版本号(之前在wsdl中看到的)

        try {
            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapSerializationEnvelope.VER11);
            envelope.bodyOut = request;//由于是发送请求，所以是设置bodyOut
            envelope.dotNet = true;//由于是.net开发的webservice，所以这里要设置为true
            HttpTransportSE httpTransportSE = new HttpTransportSE(WSDL_URI);
            httpTransportSE.debug = false;
            httpTransportSE.call("urn:HyWebServerIntf-IHyWebServer#HyWebServiceIntfMethod", envelope);//调用

            // 获取服务器响应返回的SOAP消息
            SoapObject object = (SoapObject) envelope.bodyIn;
            result = object.getProperty(0).toString();
            //     Log.e("DSDSDS", result);
            return result;

        } catch (Exception e) {
            Log.e("TAG", "getData: " + e);
        }
        return result;

    }

    public class MessageAdapter extends RecyclerView.Adapter<MessageAdapter.ViewHolder> {


        private ArrayList<Storeditem> storeditems;
        private Context mContext;

        public MessageAdapter(Context context, ArrayList<Storeditem> dataLists) {

            mContext = context;
            this.storeditems = dataLists;
        }

        public void setData(ArrayList<Storeditem> dataLists) {

            this.storeditems = dataLists;
        }

        private Context getContext() {
            return mContext;
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

            Context context = parent.getContext();
            LayoutInflater inflater = LayoutInflater.from(context);

            View contactView = inflater.inflate(R.layout.activity_articlemessage1, parent, false);

            ViewHolder viewHolder = new ViewHolder(contactView);
            return viewHolder;

        }

        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {

            //   Log.e("ASASAS",storeditems.get(position).getiKFCWS());

            holder.TextView1.setText(storeditems.get(position).getsKSMC());
            holder.TextView2.setText(storeditems.get(position).getiMZSL());
            holder.TextView3.setText(df.format(Double.parseDouble(storeditems.get(position).getfMZZJE())));
            holder.TextView4.setText(storeditems.get(position).getiZYSL());
            holder.TextView5.setText(df.format(Double.parseDouble(storeditems.get(position).getfZYZJE())));
        }

        @Override
        public int getItemCount() {
            return storeditems.size();
        }

        public class ViewHolder extends RecyclerView.ViewHolder {


            public TextView TextView1;
            public TextView TextView2;
            public TextView TextView3;
            public TextView TextView4;
            public TextView TextView5;


            public ViewHolder(View itemView) {
                super(itemView);

                TextView1 = (TextView) itemView.findViewById(R.id.TextView1);
                TextView2 = (TextView) itemView.findViewById(R.id.TextView2);
                TextView3 = (TextView) itemView.findViewById(R.id.TextView3);
                TextView4 = (TextView) itemView.findViewById(R.id.TextView4);
                TextView5 = (TextView) itemView.findViewById(R.id.TextView5);
            }
        }
    }

    @Override
    protected void updateViews(boolean isRefresh) {

    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (xh_pDialog != null){
            xh_pDialog.dismiss();
            xh_pDialog = null;
        }
    }
    @Override
    protected void onError_(Throwable e) {

    }

    @Override
    protected void onCancel_() {

    }


}
